package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.nursing.service.WechatService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
@Service
public class WechatServiceImpl implements WechatService {
    @Value("${wechat.appid}")
    private String appid;
    @Value("${wechat.secret}")
    private String secret;
    // 登录
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    /**
     *  获取微信openid
     * @param code
     * @return
     */
    @Override
    public String getOpenid(String code) {
        Map<String, Object> param = getParamConf();
        param.put("js_code",code);
        String result = HttpUtil.get(REQUEST_URL, param);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (ObjectUtil.isNotNull(jsonObject.getInt("errcode"))){
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getStr("openid");
    }

    /**
     *  获取参数
     * @return
     */
    private @NotNull Map<String, Object> getParamConf() {
        Map<String,Object> param = new HashMap<>();
        param.put("appid",appid);
        param.put("secret",secret);
        return param;
    }

    /**
     *  获取手机号
     * @param phoneCode
     * @return
     */
    @Override
    public String getPhone(String phoneCode) {
        String token = getToken();
        Map<String,Object> phoneCodeMap = new HashMap<>();
        phoneCodeMap.put("code",phoneCode);
        String result = HttpUtil.post(PHONE_REQUEST_URL + token, JSONUtil.toJsonStr(phoneCodeMap));
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (ObjectUtil.notEqual(jsonObject.getInt("errcode"),0)){
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
    }

    /**
     *  获取手机号凭证
     * @return
     */
    private String getToken() {
        String result = HttpUtil.get(TOKEN_URL, getParamConf());
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (ObjectUtil.isNotNull(jsonObject.getInt("errcode"))){
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getStr("access_token");
    }
}
